package com.lapelife.backend.filter;

import com.alibaba.fastjson.JSON;
import com.lapelife.backend.common.RedisContains;
import com.lapelife.backend.domain.entity.LoginUser;
import com.lapelife.backend.utils.JwtUtils;
import com.lapelife.backend.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class AuthenticateFilter extends OncePerRequestFilter {
    private RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        // 解析token
        String id = JwtUtils.getUserIdByJwtToken(token);
        if (!StringUtils.hasText(id)) {
            throw new RuntimeException("用户认证失败");
        }
        // 从redis中获取用户信息
        Object obj = redisUtil.get(RedisContains.USER_LOGIN + id);
        if (Objects.isNull(obj)) {
            throw new RuntimeException("用户未登录");
        }
        LoginUser loginUser = JSON.parseObject(obj.toString(), LoginUser.class);
        // 将用户信息存入SecurityContextHolder中，供其他过滤链使用
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
